<template>
  <div class="dashboard-container">
    <div class="app-container">
      <ToolBar>
        <template #before>
          共有 {{ page.total }}记录
        </template>
        <template #after>
          <el-button size="mini" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="mini" type="danger" @click="exportData">导出</el-button>
          <el-button size="mini" type="primary" @click="showDialog=true">新增员工</el-button>
        </template>
      </ToolBar>
      <el-card v-loading="loading">
        <el-table
          style="width: 100%"
          border
          :data="list"
        >
          <el-table-column
            type="index"
            label="序号"
            sortable=""
          />
          <el-table-column
            prop="username"
            label="姓名"
            sortable=""
          />
          <el-table-column
            label="头像"
          >
            <template v-slot="{row}">
              <img
                v-imageerror="defaultImg"
                :src="row.staffPhoto"
                style="width: 80px; height: 80px;border-radius: 50%"
                alt=""
                @click="showImg(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column
            label="工号"
            sortable=""
            prop="workNumber"
          />
          <el-table-column
            prop="formOfEmployment"
            label="聘用形式"
            sortable=""
            :formatter="formatEmployment"
          />
          <el-table-column
            label="部门"
            sortable=""
            prop="departmentName"
          />
          <el-table-column
            label="入职时间"
            sortable=""
            prop="timeOfEntry"
            align="center"
          >
            <!-- 作用域插槽-->
            <template v-slot="{row}">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column
            label="账户状态"
            sortable=""
            prop="enableState"
          >
            <template v-slot="{row}">
              <el-switch
                :value="row.enableState===1"
                active-color="#13ce66"
                inactive-color="#ff4949"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            sortable=""
          >
            <template v-slot="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看
              </el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="showRole(row.id)">角色</el-button>
              <el-button
                :disabled="!checkPermission('DELETE_EMPLOYEES')"
                type="text"
                size="small"
                @click="delEmployee(row.id)"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="prev, pager, next"
            :page-size.sync="page.size"
            :current-page.sync="page.page"
            :total="page.total"
            @current-change="getList"
            @size-change="getList"
          />
        </el-row>
      </el-card>
    </div>
    <add-employee :show-dialog.sync="showDialog" />
    <el-dialog title="图片预览" :visible.sync="showQrCode">
      <el-row type="flex" justify="center">
        <div>
          <canvas ref="canvas" />
        </div>
      </el-row>
    </el-dialog>
    <AssignRole ref="assignRole" :user-id="currentUserId" :show-dialog.sync="showRoleDialog" />
  </div>
</template>

<script>
import { delEmployee, getEmployeeList } from '@/api/employees'
import type from '@/api/constant/employees'
import addEmployee from '@/views/employees/components/add-employee'
import { formatDate } from '@/filters'
import Employees from '@/api/constant/employees'
import defaultImg from '@/assets/common/head.jpg'
import QRcode from 'qrcode'
import AssignRole from '@/views/employees/components/assign-role'
import checkPermission from '@/mixin/checkPermission'

export default {
  components: { addEmployee, AssignRole },
  mixins: [checkPermission],
  data() {
    return {
      currentUserId: null,
      showQrCode: false,
      defaultImg,
      page: {
        page: 1,
        size: 10,
        total: 0
      },
      list: [],
      loading: false,
      showDialog: false,
      showRoleDialog: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    showRole(id) {
      this.showRoleDialog = true
      // console.log(this.showRoleDialog)
      this.currentUserId = id
      this.$refs.assignRole.getCurrentRole(id)
    },
    showImg(url) {
      if (url) {
        this.showQrCode = true
        this.$nextTick(() => {
          QRcode.toCanvas(this.$refs.canvas, url)
        })
      } else {
        this.$message.error('该用户还未上传头像')
      }
    },
    exportData() {
      // 导出代码
      //  表头对应关系
      const headers = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      import('@/vendors/index').then(async excel => {
        // 获取需要导出的数据
        const { rows } = await getEmployeeList({ page: 1, size: this.page.total })
        const data = this.formatExcelData(rows, headers)
        excel.export_json_to_excel({
          header: Object.keys(headers),
          // data: [['黑马', '13299999999', '2020-09-09', '正式员工', '2020-09-09', '00001', '总裁办'],
          //   ['黑马', '13299999999', '2020-09-09', '正式员工', '2020-09-09', '00001', '总裁办']
          // ],
          data,
          filename: '员工信息表',
          autoWidth: true,
          bookType: 'xlsx'
        })
      })
    },
    formatExcelData(rows, headers) {
      // console.log(rows)
      return rows.map(item => {
        return Object.keys(headers).map(key => {
          if (headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime') {
            return formatDate(item[headers[key]])
          } else if (headers[key] === 'formOfEmployment') {
            const obj = Employees.hireType.find(obj => obj.id === item[headers[key]])
            return obj ? obj.value : '未知'
          }
          return item[headers[key]]
        })
      })
    },
    async getList() {
      this.loading = true
      const { rows, total } = await getEmployeeList(this.page)
      this.page.total = total
      this.list = rows
      // console.log(this.list)
      this.loading = false
    },
    formatEmployment(row, column, cellValue, index) {
      return type.hireType.find(item => item.id === cellValue)?.value || '未知'
    },
    // 删除功能
    async delEmployee(id) {
      try {
        // 弹出层提示
        await this.$confirm('是否确定删除该员工')
        // 请求接口，删除该id
        await delEmployee(id)
        // 重新渲染页面
        this.getList()
        // 提示删除成功
        this.$message.success('删除成功')
      } catch (e) {
        console.log(e)
      }
    }
  }
}
</script>

<style>

</style>
